import R from '@common/type/response';
import type { NextApiRequest, NextApiResponse } from 'next';
import jwt from "jsonwebtoken";
import { redisService } from '@common/utils/redis';

export interface AuthenticatedRequest extends NextApiRequest {
  user?: LoginUser;
}

export type AuthenticatedNextApiHandler = (
  req: AuthenticatedRequest,
  res: NextApiResponse
) => Promise<void> | void;

type Permission = {
  GET?: string;
  POST?: string;
  PUT?: string;
  DELETE?: string;
  PATCH?: string;
};

type BusinessType = 'OTHER' | 'INSERT' | 'UPDATE' | 'DELETE' | 'GRANT' | 'EXPORT' | 'IMPORT' | 'FORCE' | 'GENCODE' | 'CLEAN' | 'OPERATE';
type OperationAction = {
  title: string;
  action: BusinessType;
};
type Operation = {
  GET?: OperationAction;
  POST?: OperationAction;
  PUT?: OperationAction;
  DELETE?: OperationAction;
  PATCH?: OperationAction;
};
/**
 * 认证中间件
 * 验证请求头中的 Authorization token
 */
export function withAuth(handler: AuthenticatedNextApiHandler,permission:Permission = {}, operation:Operation = {}) {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    try {
      const authHeader = req.headers.authorization;
      
      if (!authHeader) {
        return R.unauthorized(res, '缺少认证头');
      }

      // 检查是否是 Bearer token 格式
      if (!authHeader.startsWith('Bearer ')) {
        return R.unauthorized(res, '认证头格式错误');
      }

      const token = authHeader.substring(7); // 移除 'Bearer ' 前缀
    
      if (!token) {
        return R.unauthorized(res, 'Token 为空');
      }
      if (token === 'undefined' || token === 'null') {
        return R.unauthorized(res, 'Token 无效');
      }
      // JWT 验证
      const decoded = jwt.verify(token, process.env.JWT_SECRET || '') as any;
      const uuid = decoded.uuid as string;
      const userJSON = await redisService.get('login_tokens:'+uuid);
      if(!userJSON){
        return R.unauthorized(res, 'Token UUID 无效');
      }
      const loginUser = JSON.parse(userJSON as string);
      // 将用户信息添加到请求对象中
      (req as AuthenticatedRequest).user = loginUser;
      if(permission && loginUser.userId !== 1){
        console.log(">>>>>>>>>>>>>>>>>>>",permission);
        const userPermissions = loginUser.permissions;
        const method = req.method as keyof Permission;
        const perms = permission[method];
        console.log(">>>>>>>>>>>>>>>>>>>",method,perms);
        if(perms && !userPermissions.includes(perms)){
          return R.unauthorized(res, '用户没有权限');
        }
      }
      // 调用原始处理器
      const result = await handler(req as AuthenticatedRequest, res);
      console.log(">>>>>>>>>>>>>>>>>>>",result);
      return result;
    } catch (error: any) {
      console.error('认证中间件错误:', error);
      return R.err(res, 500, '认证验证失败');
    }
  };
}
